package servlet;

import dao.InfoDao;
import entity.Info;
import entity.PageBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/info")
public class InfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private InfoDao dao = new InfoDao();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String m = request.getParameter("m");
		System.out.println("你想做" + m);
		if (m == null) {
			show(request, response);
		} else if (m.equals("del")) {
			del(request, response);
		} else if (m.equals("update")) {
			update(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("执行。。。查询");
		HttpSession session = request.getSession();
		String page = request.getParameter("page");
		int intpage = 0;
		if (page == null) {
			PageBean obj = (PageBean)session.getAttribute("pb");
			if (obj==null) {
				intpage = 1;
			} else {
				intpage = obj.getCurrPage();
			}
		} else {
			intpage = Integer.parseInt(page);
		}
		int count = dao.count();
		PageBean pb = new PageBean();
		pb.setTotalCount(count);
		pb.setCurrPage(intpage);
		request.setAttribute("pb", pb);
		session.setAttribute("pb", pb);

		List list = dao.getPage(intpage);
		request.setAttribute("infos", list);
		request.getRequestDispatcher("hero.jsp").forward(request, response);
	}


	private void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("执行。。。删除");
		String id = request.getParameter("id");
		int id2 = Integer.parseInt(id);
		dao.del(id2);
		HttpSession session = request.getSession();
		int count=dao.count();
		PageBean pb=new PageBean();
		pb.setTotalCount(count);
		pb.setCurrPage(pb.getTotalPage());
		session.setAttribute("pb", pb);
		show(request, response);
	}

	private void update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("执行。。。修改");
		int id = Integer.parseInt(request.getParameter("id"));
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String message = request.getParameter("message");
		Info info = new Info(id, name, phone, message);
		dao.update(info);
		show(request, response);
	}

}